<template>
  <div>
    <a-page-header style="border: 1px solid rgb(235, 237, 240)" title="添加商品" @back="() => this.$router.go(-1)" />
    <!-- 表单区域 -->
    <a-card style="width: 1200px; margin: 40px auto; text-align: center">
      <a-spin :spinning="confirmLoading">
        <a-form :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 12 }">
          <a-form-item label="产品名字">
            <a-input v-decorator="['title', validatorRules.val]" placeholder="请输入产品名字" />
          </a-form-item>
          <a-form-item label="生产厂家">
            <a-input v-decorator="['factory', validatorRules.val]" placeholder="请输入生产厂家" />
          </a-form-item>
          <a-form-item label="注册证编号">
            <a-input v-decorator="['regCode', validatorRules.val]" placeholder="请输入注册证编号" />
          </a-form-item>
          <a-form-item label="品牌">
            <a-select v-decorator="['brandId', validatorRules.val]">
              <a-select-option :value="item.id" v-for="(item, index) in brandUl" :key="index">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="分类">
            <a-select v-decorator="['catId', validatorRules.val]">
              <a-select-option :value="item.id" v-for="(item, index) in catIdUl" :key="index">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="产品有效期">
            <a-input v-decorator="['validDate', validatorRules.val]" placeholder="请输入产品有效期" />
          </a-form-item>
          <a-form-item label="排序">
            <a-input-number style="width: 100%" :min="1" :max="999" placeholder="排序值越大越靠前，最高999" v-decorator="['sort', validatorRules.val]" />
          </a-form-item>
          <div class="form_title">
            商品交易信息
          </div>
          <a-form-item label="计量单位">
            <a-input v-decorator="['unit', validatorRules.val]" placeholder="请输入计量单位" />
          </a-form-item>
          <!-- <a-form-item label="展示价格">
            <a-input-number style="width: 100%" placeholder="单位（元），例：一分钱，输入：0.01" :formatter="(value) => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')" :min="0" v-decorator="['price', validatorRules.val]" :precision="2" />
          </a-form-item> -->
          <div class="form_title">
            商品图片
          </div>
          <a-form-item label="商品图片">
            <ImageUpload :filePath="2" v-model="img" text="上传" :isMultiple="false" />
          </a-form-item>
          <goodsSpecModal :tableData="tableData" :key="goodsSpecModalKey" @specChang="specChang" @edit="edit"></goodsSpecModal>
          <div class="form_title">
            商品详情介绍
          </div>
          <div class="editor_box">
            <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="商品详情介绍">
              <Editor @printEdito="printEdito" ref="head"></Editor>
            </a-form-item>
          </div>
        </a-form>
        <a-button @click="submit" type="primary">提交</a-button>
      </a-spin>
    </a-card>
  </div>
</template>
<script>
import ImageUpload from '@/components/ImageUpload';
import Editor from '@/views/components/Editor';
import ApiTree from '@/api/goods/goodsList';
import GoodsBrand from '@/api/goods/goodsBrand';
import goodsCategory from '@/api/goods/goodsCategory';
import goodsSpecModal from '@/views/goods/modules/goodsSpecModal'
import { Slime, crud } from '@/mixins/slime';
import { evaFiltersMixin } from '@/mixins/evaMixin';
export default {
  name: 'goodsDetail',
  mixins: [Slime, evaFiltersMixin],
  components: { ImageUpload, Editor, goodsSpecModal,},
  data() {
    return {
      confirmLoading: false,
      id: null,
      validatorRules: {
        val: { rules: [{ required: true, message: '请输入内容!' }] },
        airconditionCode: {},
      },
      goodsSpecModalKey:0,
      brandUl: [],
      catIdUl: [],
      img: [],
      form: this.$form.createForm(this, { name: 'coordinated' }),
      tableData: [],
    };
  },
  created() {
    this.brandList();
    this.catIdList()
    if (this.$route.query.id) {
      this.id = this.$route.query.id;
      // 编辑
      this.edit();
    }
  },
  methods: {
    // 编辑
    edit() {
      this.confirmLoading = true;
      let id = this.id
      ApiTree.getDetail(id)
        .then((res) => {
          let data = res.result;
          this.$nextTick(() => {
            this.form.setFieldsValue({
              title: data.title,
              factory: data.factory,
              regCode: data.regCode,
              direction: data.direction,
              brandId: data.brandId,
              catId: data.catId,
              validDate: data.validDate,
              unit: data.unit,
              sort: data.sort,
            });
            this.tableData = data.specList
            this.img = data.img ? data.img : ''
            this.$refs.head.childFunction(data.content)
          });
        })
        .finally(() => {
          this.confirmLoading = false;
        });
    },
    // 品牌列表
    brandList() {
      GoodsBrand.getList().then((res) => {
        this.brandUl = res.result.records;
      });
    },
    //分类列表
    catIdList(){
      goodsCategory.getList().then((res) => {
        this.catIdUl = res.result.records.map((obj)=>{
          return obj = {
            ...obj,
            val: obj.id,
          }
        })
      });
    },
    //富文本编辑器
    printEdito(content) {
      this.content = content;
    },
    // 确定
    submit() {
      let that = this
      this.form.validateFields((err, values) => {
        if (!err) {
          let specList = that.tableData.map((obj)=>{
            return obj = {
              id: obj.id,
              spec: obj.spec,
              price: obj.price,
              quantity: obj.quantity,
            }
          })
          values = {
            ...values,
            content: that.content,
            img: that.img,
            specList: specList,
          };
          if (this.$route.query.id) {
            // 编辑
            values = {
              ...values,
              id: that.id,
            };
            ApiTree.getUpdate(values).then(
              (res) => {
                if(res.code == 0){
                  that.$message.success('提交成功');
                  that.form.resetFields();
                  that.$router.replace({ path: '/goods/goodsList' });
                }else{
                  that.$message.warning(res.message);
                }
              },
              (err) => {
                that.$message.warning('提交失败');
              }
            );
          } else {
            // 新增
            ApiTree.getAdd(values).then(
              (res) => {
                if(res.code == 0){
                  that.$message.success('提交成功');
                  that.form.resetFields();
                  that.$router.replace({ path: '/goods/goodsList' });
                }else{
                  that.$message.warning(res.message);
                }
              },
              (err) => {
                that.$message.warning('提交失败');
              }
            );
          }
        }
      });
    },
    // 重置
    reset() {
      this.form.resetFields();
    },
    specChang(tableData){
      this.goodsSpecModalKey = new Date().getTime() 
      this.tableData = tableData
    },
  },
};
</script>
<style scoped>
.editor_box{
  text-align: left;
}
.form_title{
  text-align: left;
  background-color: #f1f1f1;
  padding: 10px 20px;
  margin: 20px 0px;
}
</style>